<?
    final class SpaController extends PrincipioLab_Controller_Action
    {
        const ACTION_VIEW = 0;
        const ACTION_ADD = 1;
        const ACTION_EDIT = 2;
        const ACTION_CUSTOMIZE = 3;


        private function setActionViewData($action)
        {
            switch ($action)
            {
                case self::ACTION_ADD:
                    $this->view->action = "add";
                    $this->view->is_add = true;

                    Principio_Common::setButtons(
                        "Add device",
                        "ajaxSpa({id: -1, action: 'add', use_inner: true, company_id: ".$this->view->model_spa->getModelCompany()->getID().", type_id: ".$this->view->model_spa->getModelType()->getID().", ext_count: ".$this->view->model_spa->getModelType()->getExts()."});",
                        "addItem({id: -1, menu: 'spa', container: 'inner', company_id: ".$this->view->model_spa->getModelCompany()->getID().", type_id: ".$this->view->model_spa->getModelType()->getID()."});"
                    );
                    break;

                case self::ACTION_EDIT:
                    $this->view->is_add = false;

                    $model_action_menu = new Principio_Model_ActionMenu();
                    $model_action_menu->setJsAjaxFunction("Spa")->setItemID($this->view->model_spa->getID())->
                        setMenu(Principio_Model_MenuItem::fromArray(['Edit' => "edit", 'Attendant Console' => "console", 'Custom Templates' => "customize", 'View Full Profile' => "fullprofile", 'Delete' => "delete"]))->
                        setAdditionalArgs(['company_id' => $this->view->model_spa->getModelCompany()->getID(), 'type_id' => $this->view->model_spa->getModelType()->getID()]);

                    $this->view->model_action_menu = $model_action_menu;

                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxSpa({action: 'edit', id: ".$this->view->model_spa->getID().", company_id: ".$this->view->model_spa->getModelCompany()->getID().", type_id: ".$this->view->model_spa->getModelType()->getID().", ext_count: ".$this->view->model_spa->getModelType()->getExts()."});",
                        "ajaxSpa({id: ".$this->view->model_spa->getID().", action: 'edit', no_apply: true});"
                    );
                    break;

                case self::ACTION_CUSTOMIZE:
                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxSpa({action: 'customize', id: ".$this->view->model_spa->getID().", templates_count: ".$this->view->model_spa->getModelType()->getExts().", no_refresh: true});",
                        "ajaxSpa({id: ".$this->view->model_spa->getModelType()->getID().", action: 'customize', no_apply: true});"
                    );
                    break;
            };
        }


        public function fullprofileAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                $this->view->title = "Full Profile";
                $model_spa = Principio_Model_SpaMapper::fetch($this->post_data['id']);
                $this->view->request_string = "http://".Principio_Model_SettingMapper::fetch(Principio_Model_SettingMapper::SETTING_HOSTNAME)->getValue()."/prv?mac=".rawurlencode($model_spa->getMAC())."&s_id=".rawurlencode($model_spa->getSerial())."&s=9&ip=".rawurlencode($model_spa->getIP());
                $response_string = @file_get_contents($this->view->request_string);
                if (Principio_Common::checkValidity(($response_string !== false), "Can't get profile by request [".$this->view->request_string."].<br>Check your hostname option."))
                {
                    $response_string = str_replace("<", "&lt;", $response_string);
                    $response_string = str_replace(">", "&gt;", $response_string);
                    $this->view->fullprofile = $response_string;
                };
            };
        }


        private function checkUnique($field, $public_field)
        {
            $model_company = Principio_Model_SpaMapper::checkUnique($this->post_data, $field);
            if ($model_company !== false)
                Principio_Common::reportError("Device with ".$public_field." [".$this->post_data[$field]."] already exists in a company [".$model_company->getCaption()."]");
        }


        private function validate()
        {
            if ($this->checkPostItemString("mac", "MAC"))
            {
                $this->view->model_spa->setMAC($this->post_data['mac']);
                if (Principio_Common::checkValidity(preg_match("/^(([[:xdigit:]]){2}:){5}([[:xdigit:]]){2}$/", $this->post_data['mac']), "MAC has to be in XX:XX:XX:XX:XX:XX format"))
                    $this->checkUnique("mac", "MAC");
            };

            if ($this->checkPostItemString("serial", "S/N"))
            {
                $this->view->model_spa->setSerial($this->post_data['serial']);
                $this->checkUnique("serial", "serial");
            };

            if ($this->checkPostItemIP("ip", "IP"))
            {
                $this->view->model_spa->setIP($this->post_data['ip']);
                $this->checkUnique("ip", "IP");
            };


            for ($i = 0; $i < $this->view->model_spa->getModelType()->getExts(); $i++)
            {
                if (Principio_Common::checkValidity(isset($this->post_data['ext'.$i]) && ( (intval($this->post_data['ext'.$i]) > 0) || (intval($this->post_data['ext'.$i]) == -1)), "Ext ".$i." is empty." ))
                {
                    if ($this->post_data['ext'.$i] != -1)
                        $this->view->model_spa->setModelAccount($i, Principio_Model_AccountMapper::fetch(intval($this->post_data['ext'.$i])));
                }
            };

            return !Principio_Common::$is_error;
        }


        public function viewAction()
        {
            $this->editAction(self::ACTION_VIEW);
        }


        public function editAction($action = self::ACTION_EDIT)
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                $this->view->action = ($action == self::ACTION_EDIT) ? "edit" : "view";
                $this->view->model_spa = Principio_Model_SpaMapper::fetch($this->post_data['id']);

                if ($this->is_apply)
                {
                    if ($this->validate())
                    {
                        if ($this->view->model_spa->save())
                        {
                            Principio_Common::reportMessage("SPA was updated.");
                            Principio_DHCP::generate();
                        };
                    };
                };

                $this->view->collection_company = Principio_Model_Company_AbstractMapper::getNotPool();

                $this->view->ip_not_in_use = Principio_Model_SpaMapper::getIpNotInUse($this->view->model_spa->getModelCompany(), $this->view->model_spa->getIP());
                $this->view->title = "View and edit device with type [".$this->view->model_spa->getModelType()->getCaption()."]";

                $this->setActionViewData(self::ACTION_EDIT);
            }
        }


        public function customizeAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "SPA ID"))
                {
                    $this->view->model_spa = Principio_Model_SpaMapper::fetch($this->post_data['id']);

                    if ($this->is_apply)
                    {
                        for ($i = 0; $i <= $this->view->model_spa->getModelType()->getExts() + 1; $i++)
                        {
                            echo "[i = ".$i."]";

                            if (isset($this->post_data["ext".$i."_template"]))
                                $this->view->model_spa->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, $this->post_data["ext".$i."_template"]);
                            else
                                $this->view->model_spa->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, "");
                        };

                        if ($this->view->model_spa->saveTemplates())
                            Principio_Common::reportMessage("Templates were updated.");
                    };

                    $this->setActionViewData(self::ACTION_CUSTOMIZE);
                };
            };
        }


	    public function addAction()
	    {
            if ($this->is_post) 
            {
                if ( ($this->checkPostItemInt("company_id", "Company ID")) && ($this->checkPostItemInt("type_id", "Type ID")))
                {
                    $this->view->model_spa = Principio_Model_Company_AbstractMapper::fetch($this->post_data['company_id'])->createSPA(Principio_Model_TypeMapper::fetch($this->post_data['type_id']));
                    $this->setActionViewData(self::ACTION_ADD);

                    if ($this->is_apply)
                    {
                        if ($this->validate())
                        {
                            if ($this->view->model_spa->add())
                            {
                                $this->view->action = "view";
                                Principio_Common::reportMessage("Device was added.");
                                $this->view->title = "View & Edit ".$this->view->model_spa->getModelType()->getCaption()." device";
                                Principio_DHCP::generate();
                                $this->setActionViewData(self::ACTION_EDIT);
                            };
                        };
                    };

                    $this->view->ip_not_in_use = Principio_Model_SpaMapper::getIpNotInUse($this->view->model_spa->getModelCompany(), ($this->view->model_spa->getIP() == "" ? null : $this->view->model_spa->getIP()));
                    $this->view->collection_company = Principio_Model_Company_AbstractMapper::getNotPool();

                    $this->view->title = "Adding new device with type [".$this->view->model_spa->getModelType()->getCaption()."]";

                };
            };
	    }
	
        
        public function adddeviceAction()
        {
            if ( ($this->is_post) && ($this->checkPostItemInt("company_id", "Company ID")))
            {
                $this->view->title = "Adding new device";
                $this->view->collection_type = Principio_Model_TypeMapper::fetchAll();
                $this->view->company_id = $this->post_data['company_id'];
            };
        }
	
        
        public function deleteAction()
        {
            if ( ($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                if (Principio_Model_SpaMapper::fetch($this->post_data['id'])->delete())
                {
                    Principio_DHCP::generate();
                    Principio_Common::reportMessage("Device was deleted.");
                };
            };
        }
    }
?>